/*
 * TranslatorUI.java
 *
 * Created on July 16, 2008, 7:57 PM
 */
package com.elysian.translator;

import static com.google.api.services.samples.translate.cmdline.TranslateSample.googleTranslate;
import static com.google.api.services.samples.translate.cmdline.TranslateSample.googleTranslateInit;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

/**
 *
 * @author ydubey
 */
public class TranslatorUI extends javax.swing.JFrame
{

    private static Map<String, String> translations = new TreeMap<String, String>();

    static
    {
//        translations.put("Chinese-simp to English", "zh_en");
//        translations.put("Chinese-simp to Chinese-trad", "zh_zt");
//        translations.put("Chinese-trad to English", "zt_en");
//        translations.put("Chinese-trad to Chinese-simp", "zt_zh");
        translations.put("English to Chinese-simp", "en_zh_CN");
        translations.put("English to Chinese-trad", "en_zh_TW");
        translations.put("English to Dutch", "en_nl");
        translations.put("English to French", "en_fr");
        translations.put("English to German", "en_de");
        translations.put("English to Greek", "en_el");
        translations.put("English to Italian", "en_it");
        translations.put("English to Japanese", "en_ja");
        translations.put("English to Korean", "en_ko");
        translations.put("English to Portuguese", "en_pt");
        translations.put("English to Russian", "en_ru");
        translations.put("English to Spanish", "en_es");
//        translations.put("Dutch to English", "nl_en");
//        translations.put("Dutch to French", "nl_fr");
//        translations.put("French to Dutch", "fr_nl");
//        translations.put("French to English", "fr_en");
//        translations.put("French to German", "fr_de");
//        translations.put("French to Greek", "fr_el");
//        translations.put("French to Italian", "fr_it");
//        translations.put("French to Portuguese", "fr_pt");
//        translations.put("French to Spanish", "fr_es");
//        translations.put("German to English", "de_en");
//        translations.put("German to French", "de_fr");
//        translations.put("Greek to English", "el_en");
//        translations.put("Greek to French", "el_fr");
//        translations.put("Italian to English", "it_en");
//        translations.put("Italian to French", "it_fr");
//        translations.put("Japanese to English", "ja_en");
//        translations.put("Korean to English", "ko_en");
//        translations.put("Portuguese to English", "pt_en");
//        translations.put("Portuguese to French", "pt_fr");
//        translations.put("Russian to English", "ru_en");
//        translations.put("Spanish to English", "es_en");
//        translations.put("Spanish to French", "es_fr");
    }

    private TranslatorThread translatorThread;
    public static Font font = new Font("Ariel", Font.PLAIN, 12);
    private final JFileChooser fileChooser = new JFileChooser();

    private static final String TRANSLATE_ALL_RESOURCES = "translate.all_resources";
    private static final String BUNDLE_LOCATION = "resource_bundles.location";
    private static final String TRANSLATION = "translate.target";
    private static final String TRANSLATION_ALL_TARGET = "translate.all.target";
    private static final String USE_PROXY = "proxy.use";
    private static final String PROXY_IP = "proxy.ip";
    private static final String PROXY_PORT = "proxy.port";

    private static String googleAPIKey = "";

    /**
     * Creates new form TranslatorUI
     */
    public TranslatorUI()
    {
        initComponents();
        initUI();
        setSize(515, 360);
        int x, y;
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        x = new Double(d.getWidth()).intValue();
        y = new Double(d.getHeight()).intValue();
        x = (x / 2) - (getWidth() / 2);
        y = (y / 2) - (getHeight() / 2);
        setLocation(x, y);
        checkKeyForButton();
        setVisible(true);
    }

    private void checkKeyForButton()
    {
        if (!googleAPIKey.isEmpty())
        {
            this.translateButton.setEnabled(true);
        } else
        {
            this.translateButton.setEnabled(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        proxyButtonGroup = new javax.swing.ButtonGroup();
        jPanel2 = new javax.swing.JPanel();
        jPanelGoogle = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(5, 0), new java.awt.Dimension(5, 0), new java.awt.Dimension(5, 0));
        jTextFieldAPIKey = new javax.swing.JTextField();
        filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(5, 0), new java.awt.Dimension(5, 0), new java.awt.Dimension(5, 0));
        filler7 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 5), new java.awt.Dimension(0, 5), new java.awt.Dimension(32767, 5));
        translatePanel = new javax.swing.JPanel();
        translateAllInFolderCheckBox = new javax.swing.JCheckBox();
        jPanel3 = new javax.swing.JPanel();
        locationLabel = new javax.swing.JLabel();
        locationTextField = new javax.swing.JTextField();
        browseButton = new javax.swing.JButton();
        translateInAllLanguagesCheckBox = new javax.swing.JCheckBox();
        jPanel4 = new javax.swing.JPanel();
        translationLabel = new javax.swing.JLabel();
        translationComboBox = new javax.swing.JComboBox();
        filler8 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 5), new java.awt.Dimension(0, 5), new java.awt.Dimension(32767, 5));
        proxyPanel = new javax.swing.JPanel();
        directConnectionRadioButton = new javax.swing.JRadioButton();
        proxyConnectionRadioButton = new javax.swing.JRadioButton();
        jPanel1 = new javax.swing.JPanel();
        filler4 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767));
        ipAddressLabel = new javax.swing.JLabel();
        ipAddressTextField = new javax.swing.JTextField();
        filler5 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767));
        portLabel = new javax.swing.JLabel();
        portTextField = new javax.swing.JTextField();
        filler6 = new javax.swing.Box.Filler(new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 0), new java.awt.Dimension(10, 32767));
        filler10 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 5), new java.awt.Dimension(0, 5), new java.awt.Dimension(32767, 5));
        buttonsPanel = new javax.swing.JPanel();
        filler11 = new javax.swing.Box.Filler(new java.awt.Dimension(15, 0), new java.awt.Dimension(15, 0), new java.awt.Dimension(15, 32767));
        translateButton = new javax.swing.JButton();
        filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(15, 0), new java.awt.Dimension(15, 0), new java.awt.Dimension(15, 32767));
        exitButton = new javax.swing.JButton();
        filler12 = new javax.swing.Box.Filler(new java.awt.Dimension(15, 0), new java.awt.Dimension(15, 0), new java.awt.Dimension(15, 32767));
        filler9 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 5), new java.awt.Dimension(0, 5), new java.awt.Dimension(32767, 5));

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Elysian Resource Bundle Translator v1.01");
        setFont(font);
        setResizable(false);

        jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.PAGE_AXIS));

        jPanelGoogle.setBorder(javax.swing.BorderFactory.createTitledBorder("Google"));
        jPanelGoogle.setLayout(new javax.swing.BoxLayout(jPanelGoogle, javax.swing.BoxLayout.LINE_AXIS));

        jLabel1.setText("API Key");
        jPanelGoogle.add(jLabel1);
        jPanelGoogle.add(filler1);

        jTextFieldAPIKey.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jTextFieldAPIKey.setPreferredSize(new java.awt.Dimension(350, 16));
        jTextFieldAPIKey.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jTextFieldAPIKeyActionPerformed(evt);
            }
        });
        jPanelGoogle.add(jTextFieldAPIKey);
        jPanelGoogle.add(filler2);

        jPanel2.add(jPanelGoogle);
        jPanel2.add(filler7);

        translatePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Translate"));
        translatePanel.setFont(font);
        translatePanel.setLayout(new java.awt.GridLayout(4, 0, 0, 5));

        translateAllInFolderCheckBox.setFont(font);
        translateAllInFolderCheckBox.setText("Translate all resource bundles in the directory");
        translatePanel.add(translateAllInFolderCheckBox);

        jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.LINE_AXIS));

        locationLabel.setFont(font);
        locationLabel.setText("Location:");
        jPanel3.add(locationLabel);

        locationTextField.setFont(font);
        jPanel3.add(locationTextField);

        browseButton.setFont(font);
        browseButton.setText("...");
        browseButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                browseButtonActionPerformed(evt);
            }
        });
        jPanel3.add(browseButton);

        translatePanel.add(jPanel3);

        translateInAllLanguagesCheckBox.setFont(font);
        translateInAllLanguagesCheckBox.setSelected(true);
        translateInAllLanguagesCheckBox.setText("Translate in all available target languages");
        translateInAllLanguagesCheckBox.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                translateInAllLanguagesCheckBoxActionPerformed(evt);
            }
        });
        translatePanel.add(translateInAllLanguagesCheckBox);

        jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.LINE_AXIS));

        translationLabel.setFont(font);
        translationLabel.setText("Translation:");
        jPanel4.add(translationLabel);

        translationComboBox.setFont(font);
        jPanel4.add(translationComboBox);

        translatePanel.add(jPanel4);

        jPanel2.add(translatePanel);
        jPanel2.add(filler8);

        proxyPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Proxy"));
        proxyPanel.setFont(font);
        proxyPanel.setLayout(new java.awt.GridLayout(3, 0));

        proxyButtonGroup.add(directConnectionRadioButton);
        directConnectionRadioButton.setFont(font);
        directConnectionRadioButton.setSelected(true);
        directConnectionRadioButton.setText("Directly connect to the internet");
        directConnectionRadioButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                directConnectionRadioButtonActionPerformed(evt);
            }
        });
        proxyPanel.add(directConnectionRadioButton);

        proxyButtonGroup.add(proxyConnectionRadioButton);
        proxyConnectionRadioButton.setFont(font);
        proxyConnectionRadioButton.setText("Use Proxy");
        proxyConnectionRadioButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                proxyConnectionRadioButtonActionPerformed(evt);
            }
        });
        proxyPanel.add(proxyConnectionRadioButton);

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS));
        jPanel1.add(filler4);

        ipAddressLabel.setFont(font);
        ipAddressLabel.setText("IP Address:");
        jPanel1.add(ipAddressLabel);

        ipAddressTextField.setFont(font);
        ipAddressTextField.setText("co.proxy.avaya.com");
        ipAddressTextField.setEnabled(false);
        jPanel1.add(ipAddressTextField);
        jPanel1.add(filler5);

        portLabel.setFont(font);
        portLabel.setText("Port:");
        jPanel1.add(portLabel);

        portTextField.setFont(font);
        portTextField.setText("8000");
        portTextField.setEnabled(false);
        jPanel1.add(portTextField);
        jPanel1.add(filler6);

        proxyPanel.add(jPanel1);

        jPanel2.add(proxyPanel);
        jPanel2.add(filler10);

        buttonsPanel.setLayout(new java.awt.GridLayout(1, 0));
        buttonsPanel.add(filler11);

        translateButton.setFont(font);
        translateButton.setText("Translate");
        translateButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                translateButtonActionPerformed(evt);
            }
        });
        buttonsPanel.add(translateButton);
        buttonsPanel.add(filler3);

        exitButton.setFont(font);
        exitButton.setText("Exit");
        exitButton.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                exitButtonActionPerformed(evt);
            }
        });
        buttonsPanel.add(exitButton);
        buttonsPanel.add(filler12);

        jPanel2.add(buttonsPanel);
        jPanel2.add(filler9);

        getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        dispose();
}//GEN-LAST:event_exitButtonActionPerformed

    private void proxyConnectionRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_proxyConnectionRadioButtonActionPerformed
        updateProxyConfigUI();
    }//GEN-LAST:event_proxyConnectionRadioButtonActionPerformed

    private void directConnectionRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_directConnectionRadioButtonActionPerformed
        updateProxyConfigUI();
    }//GEN-LAST:event_directConnectionRadioButtonActionPerformed

    private void translateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_translateButtonActionPerformed
        translatorThread = new TranslatorThread();
        translatorThread.start();
}//GEN-LAST:event_translateButtonActionPerformed

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
        if (translateAllInFolderCheckBox.isSelected())
        {
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        } else
        {
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        }
        int choice = fileChooser.showOpenDialog(this);
        if (choice == JFileChooser.APPROVE_OPTION)
        {
            locationTextField.setText(fileChooser.getSelectedFile().getAbsolutePath());
        }
    }//GEN-LAST:event_browseButtonActionPerformed

    private void jTextFieldAPIKeyActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTextFieldAPIKeyActionPerformed
    {//GEN-HEADEREND:event_jTextFieldAPIKeyActionPerformed
        googleAPIKey = new String(this.jTextFieldAPIKey.getText().trim());
        googleTranslateInit(googleAPIKey);
        checkKeyForButton();


    }//GEN-LAST:event_jTextFieldAPIKeyActionPerformed

    private void translateInAllLanguagesCheckBoxActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_translateInAllLanguagesCheckBoxActionPerformed
    {//GEN-HEADEREND:event_translateInAllLanguagesCheckBoxActionPerformed
        if ( translateInAllLanguagesCheckBox.isSelected())
        {
            translationComboBox.setEnabled(false);
        }
        else
        {
           translationComboBox.setEnabled(true); 
        }
// TODO add your handling code here:
    }//GEN-LAST:event_translateInAllLanguagesCheckBoxActionPerformed

    private void updateProxyConfigUI()
    {
        ipAddressTextField.setEnabled(proxyConnectionRadioButton.isSelected());
        portTextField.setEnabled(proxyConnectionRadioButton.isSelected());
    }

    private String translate(String string, String targetTranslation) throws IOException
    {
        if (string.toLowerCase().startsWith("<html>"))
        {
            StringBuilder translatedHTML = new StringBuilder();
            int startTagIndex = string.indexOf("<", 0);
            int len = string.length();
            while (startTagIndex != -1 && startTagIndex < len)
            {
                int endTagIndex = string.indexOf(">", startTagIndex);
                if (endTagIndex != -1)
                {
                    translatedHTML.append(string.substring(startTagIndex, endTagIndex + 1));
                    startTagIndex = string.indexOf("<", endTagIndex);
                }
                if (startTagIndex != -1)
                {
                    String stringToTranslate = string.substring(endTagIndex + 1, startTagIndex);
                    if (stringToTranslate.length() > 0)
                    {
                        if (stringToTranslate.trim().length() > 0)
                        {
                            translatedHTML.append(translateUnit(stringToTranslate, targetTranslation));
                        } else
                        {
                            translatedHTML.append(stringToTranslate);
                        }
                    }
                }
            }
            return translatedHTML.toString();
        } else
        {
            return translateUnit(string, targetTranslation);
        }
    }

    private String translateUnit(String string, String targetTranslation) throws IOException
    {

        return googleTranslate(string, targetTranslation, "");
//        String submitURL = "http://babelfish.yahoo.com/translate_txt";
//        Properties properties = new Properties();
//        properties.put("trtext", string);
//        properties.put("lp", targetTranslation);
//        String response = new String(download(submitURL, properties));
//        int index = response.indexOf("<div id=\"result\">");
//        if (index != -1)
//        {
//            int start = index + "<div id=\"result\"><div style=\"padding:0.6em;\">".length();
//            int end = response.indexOf("</div>", start);
//            String translated = response.substring(start, end);
//            translated = HTMLSpclCharsConverter.convert(translated);
//            return translated;
//        }
//        return null;
    }

    private static String createURL(String urlToDownload, Properties properties) throws UnsupportedEncodingException
    {
        StringBuilder stringBuilder = new StringBuilder(urlToDownload);
        Set keys = properties.keySet();
        String pre = "?";
        for (Object key : keys)
        {
            stringBuilder.append(pre);
            pre = "&";
            stringBuilder.append(URLEncoder.encode(key.toString(), "UTF-8"));
            stringBuilder.append("=");
            stringBuilder.append(URLEncoder.encode(properties.get(key).toString(), "UTF-8"));
        }
        return stringBuilder.toString();
    }

    private byte[] download(String urlToDownload, Properties properties) throws IOException
    {
        String downloadURL = createURL(urlToDownload, properties);
        HttpClient client = new HttpClient();
        if (proxyConnectionRadioButton.isSelected())
        {
            client.getHostConfiguration().setProxy(ipAddressTextField.getText(), Integer.parseInt(portTextField.getText()));
        }
        GetMethod method = new GetMethod(downloadURL);
        //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        byte[] responseBody = null;
        try
        {
            int statusCode = client.executeMethod(method);
            if (statusCode != HttpStatus.SC_OK)
            {
                System.err.println("Method failed: " + method.getStatusLine());
            }
            responseBody = method.getResponseBody();
        } finally
        {
            method.releaseConnection();
        }
        return responseBody;
    }

    public static String getTranslationKey(String text)
    {
        Set<String> keys = translations.keySet();
        for (String key : keys)
        {
            if (translations.get(key).equals(text))
            {
                return key;
            }
        }
        return null;
    }

    private void initUI()
    {
        Set<String> availableTranslations = translations.keySet();
        for (String availableTranslation : availableTranslations)
        {
            translationComboBox.addItem(availableTranslation);
        }
        File confFile = new File("translator.properties");
        if (confFile.exists() && confFile.isFile())
        {
            try
            {
                Properties toolProperties = new Properties();
                toolProperties.load(new FileInputStream(confFile));
                translateAllInFolderCheckBox.setSelected(Boolean.parseBoolean(toolProperties.getProperty(TRANSLATE_ALL_RESOURCES)));
                locationTextField.setText(toolProperties.getProperty(BUNDLE_LOCATION));
                translationComboBox.setSelectedItem(toolProperties.getProperty(TRANSLATION));
                translateInAllLanguagesCheckBox.setSelected(Boolean.parseBoolean(toolProperties.getProperty(TRANSLATION_ALL_TARGET)));
                proxyConnectionRadioButton.setSelected(Boolean.parseBoolean(toolProperties.getProperty(USE_PROXY)));
                ipAddressTextField.setText(toolProperties.getProperty(PROXY_IP));
                portTextField.setText(toolProperties.getProperty(PROXY_PORT));
                updateProxyConfigUI();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void dispose()
    {
        Properties toolProperties = new Properties();
        toolProperties.setProperty(TRANSLATE_ALL_RESOURCES, translateAllInFolderCheckBox.isSelected() + "");
        toolProperties.setProperty(BUNDLE_LOCATION, locationTextField.getText());
        toolProperties.setProperty(TRANSLATION, translationComboBox.getSelectedItem().toString());
        toolProperties.setProperty(TRANSLATION_ALL_TARGET, translateInAllLanguagesCheckBox.isSelected() + "");
        toolProperties.setProperty(USE_PROXY, proxyConnectionRadioButton.isSelected() + "");
        toolProperties.setProperty(PROXY_IP, ipAddressTextField.getText());
        toolProperties.setProperty(PROXY_PORT, portTextField.getText());
        try
        {
            File confFile = new File("translator.properties");
            toolProperties.store(new FileOutputStream(confFile), "Translator Configurations");
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        super.dispose();
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton browseButton;
    private javax.swing.JPanel buttonsPanel;
    private javax.swing.JRadioButton directConnectionRadioButton;
    private javax.swing.JButton exitButton;
    private javax.swing.Box.Filler filler1;
    private javax.swing.Box.Filler filler10;
    private javax.swing.Box.Filler filler11;
    private javax.swing.Box.Filler filler12;
    private javax.swing.Box.Filler filler2;
    private javax.swing.Box.Filler filler3;
    private javax.swing.Box.Filler filler4;
    private javax.swing.Box.Filler filler5;
    private javax.swing.Box.Filler filler6;
    private javax.swing.Box.Filler filler7;
    private javax.swing.Box.Filler filler8;
    private javax.swing.Box.Filler filler9;
    private javax.swing.JLabel ipAddressLabel;
    private javax.swing.JTextField ipAddressTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanelGoogle;
    private javax.swing.JTextField jTextFieldAPIKey;
    private javax.swing.JLabel locationLabel;
    private javax.swing.JTextField locationTextField;
    private javax.swing.JLabel portLabel;
    private javax.swing.JTextField portTextField;
    private javax.swing.ButtonGroup proxyButtonGroup;
    private javax.swing.JRadioButton proxyConnectionRadioButton;
    private javax.swing.JPanel proxyPanel;
    private javax.swing.JCheckBox translateAllInFolderCheckBox;
    private javax.swing.JButton translateButton;
    private javax.swing.JCheckBox translateInAllLanguagesCheckBox;
    private javax.swing.JPanel translatePanel;
    private javax.swing.JComboBox translationComboBox;
    private javax.swing.JLabel translationLabel;
    // End of variables declaration//GEN-END:variables

    public class TranslatorThread extends Thread
    {

        private boolean alive = true;

        @Override
        public void run()
        {
            File[] resourceBundles = null;
            File parentFolder = null;
            File location = new File(locationTextField.getText());
            if (translateAllInFolderCheckBox.isSelected())
            {
                if (location.exists() && location.isDirectory())
                {
                    resourceBundles = location.listFiles(new FileFilter()
                    {
                        public boolean accept(File file)
                        {
                            if (file.isFile() && file.getName().toLowerCase().endsWith(".properties"))
                            {
                                return true;
                            } else
                            {
                                return false;
                            }
                        }
                    });
                } else
                {
                    JOptionPane.showMessageDialog(TranslatorUI.this, "<html>Folder <i>" + location.getAbsolutePath() + "</i> does not exist or is not a folder!</html>", "Error!", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else if (location.exists() && location.isFile() && location.getName().toLowerCase().endsWith(".properties"))
            {
                resourceBundles = new File[]
                {
                    location
                };
            } else
            {
                JOptionPane.showMessageDialog(TranslatorUI.this, "<html>File <i>" + location.getAbsolutePath() + "</i> does not exist or is not a valid properties file!</html>", "Error!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            Set<String> targetTranslations = new HashSet<String>();
            String chosenTranslation = translations.get((String) translationComboBox.getSelectedItem());
            if (translateInAllLanguagesCheckBox.isSelected())
            {
                String chosenTranslationSource = chosenTranslation.substring(0, chosenTranslation.indexOf("_"));
                Set<String> availableTargetTranslations = translations.keySet();
                for (String availableTargetTranslation : availableTargetTranslations)
                {
                    String translationKey = translations.get(availableTargetTranslation);
                    if (translationKey.startsWith(chosenTranslationSource))
                    {
                        targetTranslations.add(translationKey);
                    }
                }
            } else
            {
                targetTranslations.add(chosenTranslation);
            }
            WaitWhileTranslatingDialog waitWhileTranslatingDialog = null;
            try
            {
                waitWhileTranslatingDialog = new WaitWhileTranslatingDialog(TranslatorUI.this, this);
                translateButton.setEnabled(false);
                Properties i18nProperties = null;
                for (File resourceBundle : resourceBundles)
                {
                    parentFolder = resourceBundle.getParentFile();
                    if (i18nProperties == null)
                    {
                        i18nProperties = new Properties();
                        if (!translateInAllLanguagesCheckBox.isSelected())
                        {
                            try
                            {
                                FileInputStream inputStream = new FileInputStream(new File(parentFolder, "i18n.properties"));
                                i18nProperties.load(inputStream);
                                inputStream.close();
                            } catch (IOException e)
                            {
                            }

                        }
                    }
                    Properties sourceProperties = new Properties();
                    FileInputStream inputStream = new FileInputStream(resourceBundle);
                    sourceProperties.load(inputStream);
                    inputStream.close();
                    for (String targetTranslation : targetTranslations)
                    {
                        String outputFileName = resourceBundle.getName();
                        outputFileName = outputFileName.substring(0, outputFileName.lastIndexOf("."));
                        outputFileName += targetTranslation.substring(targetTranslation.indexOf("_")) + ".properties";
                        File outputFile = new File(resourceBundle.getParent(), outputFileName);
                        String translationName = getTranslationKey(targetTranslation);
                        if (i18nProperties != null)
                        {
                            i18nProperties.setProperty(translationName.substring(translationName.lastIndexOf(" ") + 1), targetTranslation.substring(targetTranslation.indexOf("_") + 1));
                        }
                        Properties translatedProperties = new Properties();
                        Set keys = sourceProperties.keySet();
                        waitWhileTranslatingDialog.showTranslationTarget(translationName);
                        for (Object key : keys)
                        {
                            String source = sourceProperties.getProperty(key.toString());
                            if (source == null)
                            {
                                source = key.toString();
                                waitWhileTranslatingDialog.showTranslationAbsolute("<html>WARNING: No Text for <i>'" + key + "'</i> found.</html>");
                            } else
                            {
                                waitWhileTranslatingDialog.showTranslation(source);
                            }
                            if (!alive)
                            {
                                return;
                            }
                            String tt = targetTranslation.substring(targetTranslation.indexOf("_") + 1);
                            if (source != null)
                            {
                                String trSource;
                                try
                                {
                                    trSource = translate(source, tt);
                                    if (trSource == null)
                                    {
                                        trSource = source;
                                    }
                                } catch (Exception e)
                                {
                                    trSource = source;
                                }
                                translatedProperties.setProperty(key.toString(), trSource);
                            }
                        }
                        FileOutputStream outputStream = new FileOutputStream(outputFile);
                        translatedProperties.store(outputStream, chosenTranslation);
                        outputStream.close();
                    }
                }
                FileOutputStream outputStream = new FileOutputStream(new File(parentFolder, "i18n.properties"));
                i18nProperties.store(outputStream, "Available translations");
            } catch (Exception e)
            {
                JOptionPane.showMessageDialog(TranslatorUI.this, "<html>Exception: <i>" + e.getLocalizedMessage() + "</i></html>", "Error!", JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            } finally
            {
                waitWhileTranslatingDialog.dispose();
                translateButton.setEnabled(true);
            }
        }

        void kill()
        {
            alive = false;
        }
    }

}
